package org.jetnuke.modules.pictures;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.Picture;

public class GetPicture implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(GetPicture.class);

	int pid;

	public void setPid(int pid) {
		this.pid = pid;
	}

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		Picture picture = DataAccessDriver.getInst().newPictureDAO()
				.retrieveByPK(pid);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		String initPath = SystemGlobals
				.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/pictures/" + picture.getUID() + "/";
		// String path = sc.getRealPath(initPath);
		File pathDir = new File(initPath);
		if (!pathDir.exists()) {
			pathDir.mkdirs();
		}
		File f = null;

		f = new File(pathDir, picture.getFILENAME());
		response.setContentType(picture.getMIMETYPE());
		BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(f));
		byte[] b = new byte[4096];

		while ((bis.read(b)) != -1) {
			baos.write(b);
		}
		bis.close();
		response.setContentLength(baos.size());
		OutputStream os = response.getOutputStream();
		baos.writeTo(os);

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

}
